import BaseSimpleFSMState from "./BaseSimpleFSMState.";


export default class SimpleFSM {
    private _currentState: BaseSimpleFSMState;
    private _stateMap: Map<number, BaseSimpleFSMState> = new Map();

    public addState(stateId: number, state: BaseSimpleFSMState, userData?: any): void {
        state.setState(stateId);
        state.setUserData(userData);
        this._stateMap.set(stateId, state);
    }

    /**
     * 前往某个状态
     * @param state 状态id
     * @param userData 自定义参数
     * @returns 是否切换成功
     */
    public goToState(stateId: number, userData?: any): boolean {
        let prevState = -1;

        if (this._currentState) {
            this._currentState.end(stateId);
            prevState = this._currentState.getStateId();
            this._currentState = null;
        }
        if (this._stateMap.has(stateId)) {
            this._currentState = this._stateMap.get(stateId);
            if (userData) {
                this._currentState.setUserData(userData);
            }

            this._currentState.begin(prevState);
            return true;
        }
        return false;
    }

    public tick(dt: number): void {
        this._currentState?.tick(dt);
    }

    public getCurrentStateId(): number {
        if (!this._currentState) {
            return -1;
        }
        return this._currentState?.getStateId();
    }

    public getCurrentState(): BaseSimpleFSMState {
        return this._currentState;
    }

    public getState<T extends BaseSimpleFSMState>(stateId: number): T {
        return this._stateMap.get(stateId) as T;
    }

    public gotoNone(): void {
        this._currentState?.end(-1);
        this._currentState = null;
    }
}